/**
 * 登录路由组件
 */

import React, {Component} from 'react'
import {
    NavBar,
    WingBlank,
    List,
    InputItem,
    WhiteSpace,
    Button
} from "antd-mobile";


import {connect} from 'react-redux'
import {Redirect} from 'react-router-dom'

import {login, register} from '../../redux/actions'


import Logo from '../../components/logo/logo'

const ListItem = List.Item


class Login extends Component{

    /*
    * 保存收集的数据
    * */
    state = {
        username: '',   // 用户名
        password: '',   // 密码
    }

    /*
    * 登录
    * */
    login = () => {
        console.log(this.state)
        this.props.login(this.state)
    }

    /*
    * 处理输入数据的改变,更新对应的状态
    * */
    handleChange = (name, val) => {

        // 更新状态
        this.setState({
            /*不用[] 就是字符串  我们需要的是一个变量
            * 属性名不是name,而是name的值
            * */
            [name]:val
        })
    }

    /*
    *   跳转到注册页面
    * */
    toRegister = () => {
        this.props.history.replace('/register')
    }


    render() {


        const {msg, redirectTo} = this.props.user
        // 如果redirectTo有值,就需要重定向到指定的路由
        if (redirectTo) {
            return <Redirect to={redirectTo}/>
        }

        return (
            <div>
                <NavBar className='qianduan_Nav'>中&nbsp;国&nbsp;联&nbsp;通</NavBar>
                <WhiteSpace/>
                <Logo />
                <WhiteSpace/>
                <WhiteSpace/>
                <WingBlank>
                    <List>
                        {msg ? <div className='error-msg'>{msg}</div>: null}
                        <WhiteSpace/>
                        <InputItem
                            placeholder='请输入用户名'
                            onChange={val => {this.handleChange('username', val)}}>用户名:</InputItem>
                        <WhiteSpace/>
                        <InputItem
                            placeholder='请输入密码'
                            type="password" onChange={val => {this.handleChange('password', val)}}>密&nbsp;&nbsp;&nbsp;码:</InputItem>
                        <WhiteSpace/>
                        <WhiteSpace/>
                        <WhiteSpace/>

                        <Button type="primary" onClick={this.login}>登&nbsp;&nbsp;&nbsp;陆</Button>
                        <WhiteSpace/>
                        <Button onClick={this.toRegister}>快去注册</Button>
                    </List>
                </WingBlank>
            </div>
        )
    }
}

export default connect(
    state => ({user:state.user}),
    {login}
)(Login)


